package cn.kuaipan.android.openapi;

import com.easyfun.healthmagicbox.comm.PicturesDownloadTask;
import com.easyfun.healthmagicbox.comm.PicturesUploadTask;
import com.easyfun.healthmagicbox.pojo.Picture;
import com.easyfun.healthmagicbox.util.SharedPreferencesUtil;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import cn.kuaipan.android.openapi.AuthActivity;
import cn.kuaipan.android.openapi.AuthSession;
import cn.kuaipan.android.openapi.KuaipanAPI;
import cn.kuaipan.android.openapi.session.AccessTokenPair;
import cn.kuaipan.android.openapi.session.AppKeyPair;
import cn.kuaipan.android.openapi.tasks.DownloadTask;
import cn.kuaipan.android.openapi.tasks.MkdirTask;
import cn.kuaipan.android.openapi.tasks.UploadTask;
import cn.kuaipan.android.sdk.oauth.Session.Root;

public class KuaiPanManager {
	private static KuaiPanManager instance = null;
	private static Boolean isLogged = false;
	private Context ctx;
	private int authType;

    KuaipanAPI mApi;
    private AuthSession mAuthSession;
	private String TAG;
    
	private KuaiPanManager(Context ctx)
	{
		this.ctx = ctx;
	}
	public static KuaiPanManager getInstance(Context ctx)
	{
		synchronized(isLogged)
		{
			if (instance == null)
			{
				instance = new KuaiPanManager(ctx);
				instance.loginKuaiPan();
			}
		}
		return instance;
	}
	
	public void loginKuaiPan()
	{
		// We create a new AuthSession so that we can use the Kuaipan API.
	    mAuthSession = buildSession();
	    mApi = new KuaipanAPI(ctx, mAuthSession);
	    isLogged = mApi.isAuthorized();
	    return;
	}
	
	private AuthSession buildSession() {
        String APP_KEY = SharedPreferencesUtil.getInstance(ctx).getAPP_KEY();
        if ((APP_KEY ==null) ||(APP_KEY.length() == 0))
        {
        	APP_KEY = "xcPWBQPe4Ji88tXJ";
        }
		String APP_SECRET = SharedPreferencesUtil.getInstance(ctx).getAPP_SECRET();
		if ((APP_SECRET ==null) ||(APP_SECRET.length() == 0))
        {
			APP_SECRET = "8I65AEjL17bYfyut";
        }
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
        AuthSession session;

        String[] stored = getKeys();
        if (stored != null) {
            AccessTokenPair accessToken = new AccessTokenPair(stored[0],
                    stored[1]);
            if (TextUtils.isEmpty(stored[2])) {

            }
            authType = !TextUtils.isEmpty(stored[2]) ? Integer
                    .valueOf(stored[2]) : 0;
            session = new AuthSession(appKeyPair, accessToken, Root.APP_FOLDER);
            this.authType = Integer.valueOf(stored[3]);
        } else {
            session = new AuthSession(appKeyPair, Root.APP_FOLDER);
        }

        return session;
    }
	
	 /**
     * Shows keeping the access keys returned from Trusted Authenticator in a
     * local store, rather than storing user name & password, and
     * re-authenticating each time (which is not to be done, ever).
     * 
     * @return Array of [access_key, access_secret, uid, auth_type], or null if
     *         none stored
     */
    private String[] getKeys() {
        
        String key = SharedPreferencesUtil.getInstance(ctx).getACCESS_KEY_NAME();
        String secret = SharedPreferencesUtil.getInstance(ctx).getACCESS_SECRET_NAME();
        String uid = SharedPreferencesUtil.getInstance(ctx).getACCESS_UID_NAME();
        String authType = SharedPreferencesUtil.getInstance(ctx).getACCESS_AUTH_TYPE_NAME();
        
        key="01b1050f57ad6e700e3fddf6";
        secret="4a120e23913c41a9acf71b57d615bb46";
        uid="28378383";
        authType="0";
        
        if (key != null && secret != null) {
            String[] ret = new String[4];
            ret[0] = key;
            ret[1] = secret;
            ret[2] = uid;
            ret[3] = authType;
            return ret;
        } else {
            return null;
        }
    }
    
    public void logOut()
    {
    	mApi.unAuthorize();
    }

    /**
     * This should never ever be called.
     * It will show a login page to get user login KuaiPan
     */
    private void onClickLogin() {
        //if (!mLoggedIn) {
            // Start the authentication
            mApi.startAuthForResult();
        //} else {
        //    logOut();
        //}
    }
    
	public void uploadFile(PicturesUploadTask task)
	{
		RequestBase request = new RequestBase();
		request.setApi(mApi);
		String remoteFilename =  task.getFilename();
		request.setFilePath(remoteFilename);
		Log.v(TAG, "ready to start task:" + remoteFilename);
		new UploadTask(task).start(request);
	}
	
	public void uploadFile(String personID, String localfile, String remoteFilename)
	{
		RequestBase request = new RequestBase();
		request.setApi(mApi);
		request.setFilePath(remoteFilename);
		Log.v(TAG, "ready to start task:" + remoteFilename);
		new UploadTask(personID,ctx).start(request);
	}
    
	public void downloadFile(String personID, String remoteFilename)
	{
		RequestBase request = new RequestBase();
		request.setApi(mApi);
		request.setRemotePath(remoteFilename);
		Log.v(TAG, "ready to start task:" + remoteFilename);
		new DownloadTask(ctx,personID).start(request);
	}
	
	public void downloadFile(PicturesDownloadTask task, Picture pic)
	{

        RequestBase request = new RequestBase();
        request.setApi(mApi);
        request.setRemotePath(pic.getFilename());
        new DownloadTask(task,pic).start(request);
	}
	public void mkdir(PicturesUploadTask picturesUploadTask) {
		RequestBase request = new RequestBase();
        request.setApi(mApi);
        String remoteFilename =  picturesUploadTask.getPersonID();
		request.setFilePath(remoteFilename);
        new MkdirTask(picturesUploadTask).start(request);
		
	}
	
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode,
//            Intent intent) {
//
//        Log.v(TAG, "requestCode:" + requestCode + " resultCode:" + resultCode);
//
//        if (requestCode == AuthActivity.AUTH_REQUEST_CODE) {
//
//            Log.v(TAG, "resultCode: " + getAuthResultName(resultCode));
//            Log.v(TAG, "ResultData:  " + intent);
//
//            if (intent == null) {
//                return;
//            }
//
//            if (resultCode == AuthActivity.SUCCESSED && intent != null) {
//                Bundle values = intent.getExtras();
//                final String accessToken = values
//                        .getString(AuthActivity.EXTRA_ACCESS_TOKEN);
//                final String accessSecret = values
//                        .getString(AuthActivity.EXTRA_ACCESS_SECRET);
//                final String uid = values.getString(AuthActivity.EXTRA_UID);
//                authType = values.getInt(AuthActivity.EXTRA_AUTH_TYPE);
//
//                Log.v(TAG, "Authorized by " + getAuthName(authType) + " server");
//
//                final String error_code = values
//                        .getString(AuthActivity.EXTRA_ERROR_CODE);
//                Log.v(TAG, "!!!accessToken=" + accessToken + "\n"
//                        + "accessSecret=" + accessSecret + "\n" + "uid=" + uid
//                        + "\n" + "error_code" + error_code);
//
//                /**
//                 * set validate access token pair, then isAuthorized will return
//                 * true
//                 */
//                mApi.setAccessToken(accessToken, accessSecret);
//
//                setLoggedIn(mApi.isAuthorized());
//
//                // store all concern values into preference
//                storeKeys(accessToken, accessSecret, uid,
//                        String.valueOf(authType));
//            }
//        } else {
//            switch (requestCode) {
//                case PHOTO_SELECTED:
//                    if (resultCode == RESULT_OK) {
//                        Uri selectedImage = intent.getData();
//                        RequestBase request = new RequestBase();
//                        request.setApi(mApi);
//                        request.setFileUri(selectedImage);
//                        Log.v(TAG, "ready to start task:" + selectedImage);
//                        new UploadTask(this).start(request);
//                    }
//                    break;
//                default:
//                    break;
//            }
//        }
//    }
//    
//    private String getAuthName(int authType) {
//        if (authType == AuthActivity.WEIBO_AUTH) {
//            return "[weibo]";
//        } else if (authType == AuthActivity.QQ_AUTH) {
//            return "[qq]";
//        } else if (authType == AuthActivity.XIAOMI_AUTH) {
//            return "[xiaomi]";
//        } else if (authType == AuthActivity.KUAIPAN_AUTH) {
//            return "[kuaipan]";
//        }
//        return "[UnKnown]";
//    }
}
